package com.android.hidephotosplus;

import java.io.File;
import java.util.ArrayList;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.android.hidephotosplus.adapter.AlbumAdapter;
import com.android.hidephotosplus.interfaces.MInterface.onTask;
import com.android.hidephotosplus.model.ModelAlbum;
import com.android.hidephotosplus.model.ModelMedia;
import com.android.hidephotosplus.preference.IntPref;
import com.android.hidephotosplus.preference.StringPref;
import com.android.hidephotosplus.util.Camera;
import com.android.hidephotosplus.util.Config;
import com.android.hidephotosplus.util.Util;

public class HiddenGalleryFragment extends GalleryFragment {

	private Receiver receiver;

	private ArrayList<ModelAlbum> arrAlbums = new ArrayList<ModelAlbum>();

	private ArrayList<ModelAlbum> arrAlbumsSelected = new ArrayList<ModelAlbum>();

	private AlbumAdapter mAlbumAdapter;

	private int position = 0;

	public String navigationSelected = null;

	private boolean isCheckAll = false;

	public Camera camera;

	public ActionMode mActionMode;

	private String[] listNavigation;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		registerBroadcast();
		position = 0;
		listNavigation = getResources().getStringArray(R.array.listNavigation);
		setupHiddenGalleryFragment(listNavigation[IntPref.getPreference(
				getSherlockActivity(), Config.KEY_POSITION_LIST_NAVIGATION, 0)]);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.gallery_fragment, null);
		textEmpty = (TextView) view.findViewById(R.id.textEmpty);
		textEmpty.setText(getString(R.string.empty_album));
		progressBar = (ProgressBar) view.findViewById(R.id.progressEmpty);
		mGridView = (GridView) view.findViewById(R.id.gridAlbum);
		mGridView.setEmptyView(progressBar);
		mGridView.setOnItemClickListener(this);
		mGridView.setOnItemLongClickListener(this);
		mGridView.setOnScrollListener(this);

		mAlbumAdapter = new AlbumAdapter(getActivity(), arrAlbums, false);
		mGridView.setAdapter(mAlbumAdapter);
		mGridView.setEmptyView(textEmpty);
		mAlbumAdapter.notifyDataSetChanged();

		return view;
	}

	public void setupHiddenGalleryFragment(String type_media) {
		if (type_media.equals(getActivity().getString(R.string.all_media))) {
			navigationSelected = getString(R.string.all_media);
			arrAlbums.clear();
			arrAlbums.addAll(mDbHelper.getAllAlbum());
		} else if (type_media.equals(getActivity().getString(R.string.photos))) {
			navigationSelected = getString(R.string.photos);
			arrAlbums.clear();
			arrAlbums.addAll(mDbHelper.getAllAlbumPhotos());
		} else {
			navigationSelected = getString(R.string.videos);
			arrAlbums.clear();
			arrAlbums.addAll(mDbHelper.getAllAlbumVideos(null));
		}
		if (mAlbumAdapter != null) {
			mAlbumAdapter.notifyDataSetChanged();
		}
	}

	private void registerBroadcast() {
		try {
			IntentFilter filter = new IntentFilter();
			filter.addAction(Config.ACTION_SEND_TYPE_MEDIA);
			filter.addAction(Config.ACTION_SEND_ARR_ALBUM_STOCK_TO_HIDDEN);
			filter.addAction(Config.ACTION_SEND_NAME_ALBUM_TO_HIDDEN);
			receiver = new Receiver();
			getActivity().registerReceiver(receiver, filter);
		} catch (Exception e) {
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		try {
			getActivity().unregisterReceiver(receiver);
		} catch (Exception e) {
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		this.position = position;
		if (!isStartActionMode) {
			Intent intent = new Intent(getActivity(), ActivityAlbumView.class);
			intent.putExtra(Config.KEY_ALBUM_HIDDEN,
					mAlbumAdapter.getItem(position));
			intent.putExtra(Config.KEY_NAVIGATION_SELECTED, navigationSelected);
			getSherlockActivity().startActivityFromFragment(this, intent,
					Config.REQUEST_CODE_ALBUMVIEW_HIDDEN);
		} else {
			setSelectedUnSelected(position, arrAlbums, arrAlbumsSelected,
					mAlbumAdapter, mActionMode);
		}

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
			int position, long arg3) {
		if (!isStartActionMode) {
			mActionMode = getSherlockActivity().startActionMode(
					new AnActionMode(false));
		}
		setSelectedUnSelected(position, arrAlbums, arrAlbumsSelected,
				mAlbumAdapter, mActionMode);
		return true;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (view.getId() == R.id.gridAlbum) {
			if (scrollState == SCROLL_STATE_FLING) {
				mAlbumAdapter.setScroolState(true);
			} else {
				mAlbumAdapter.setScroolState(false);
				mAlbumAdapter.notifyDataSetChanged();
			}
		}

	}

	private void showDialogAddAlbum() {
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setTitle(getString(R.string.add_new_album));
		final EditText editText = new EditText(getActivity());
		builder.setView(editText);
		builder.setPositiveButton(getString(R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						String nameAlbum = editText.getText().toString();
						if (TextUtils.isEmpty(editText.getText().toString())) {
							Config.showToastShort(getActivity(),
									getString(R.string.please_enter_name_album));
						} else {
							if (!mDbHelper.checkExistsAlbum(nameAlbum)) {
								int typeStore = Integer.parseInt(StringPref
										.getPreference(getActivity(),
												Config.KEY_STORAGE, "1"));
								String pathAlbum = Config
										.getPathFinal(typeStore) + nameAlbum;
								long idAlbum = mDbHelper.insertAlbum(nameAlbum,
										pathAlbum, typeStore);
								File file = new File(pathAlbum);
								if (!file.exists())
									file.mkdirs();
								ModelAlbum item = new ModelAlbum();
								item.setNameAlbum(nameAlbum);
								item.setPathAlbum(pathAlbum);
								item.setIdAlbum(idAlbum);
								arrAlbums.add(0, item);
								mAlbumAdapter.notifyDataSetChanged();
							} else
								Toast.makeText(getActivity(),
										getString(R.string.album_exists),
										Toast.LENGTH_LONG).show();

						}

					}
				});
		builder.setNegativeButton(getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		builder.show();
	}

	private class Receiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(
					Config.ACTION_SEND_ARR_ALBUM_STOCK_TO_HIDDEN)) {
				if (intent.getExtras() != null) {
					ArrayList<ModelAlbum> arrAlbumsStock = intent
							.getParcelableArrayListExtra(Config.KEY_ARR_ALBUM_STOCK);
					for (ModelAlbum album : arrAlbumsStock) {
						boolean isExists = false;
						for (ModelAlbum albumHidden : arrAlbums) {
							if (album.getNameAlbum().equals(
									albumHidden.getNameAlbum())) {
								isExists = true;
								setMediaOfAlbum(albumHidden);
							}
						}
						if (!isExists) {
							ArrayList<ModelAlbum> arrAlbumsHidden = getNewAlbum(album);
							if (arrAlbumsHidden == null)
								arrAlbumsHidden = new ArrayList<ModelAlbum>();
							arrAlbums.addAll(arrAlbumsHidden);
						}

					}
					mAlbumAdapter.notifyDataSetChanged();
				}
			} else if (intent.getAction().equals(
					Config.ACTION_SEND_NAME_ALBUM_TO_HIDDEN)) {
				if (intent.getExtras() != null) {
					String nameAlbum = intent.getExtras().getString(
							Config.KEY_NAME_ALBUM_HIDDEN);
					boolean isExists = false;
					for (ModelAlbum albumHidden : arrAlbums) {
						if (nameAlbum.equals(albumHidden.getNameAlbum())) {
							isExists = true;
							setMediaOfAlbum(albumHidden);
						}
					}
					if (!isExists) {
						ArrayList<ModelAlbum> arrAlbumsHidden = getNewAlbumByName(nameAlbum);
						if (arrAlbumsHidden == null)
							arrAlbumsHidden = new ArrayList<ModelAlbum>();
						arrAlbums.addAll(arrAlbumsHidden);
					}
					mAlbumAdapter.notifyDataSetChanged();
				}
			}
		}

	}

	public class AnActionMode implements ActionMode.Callback {
		private boolean isPublic;

		public AnActionMode(boolean isPublic) {
			this.isPublic = isPublic;
		}

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			MenuInflater inflater = mode.getMenuInflater();
			if (isPublic)
				inflater.inflate(R.menu.actionmode_album_view_stock, menu);
			else
				inflater.inflate(R.menu.actionmode_album_view_hidden, menu);
			isStartActionMode = true;
			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			switch (item.getItemId()) {
			case R.id.menu_check_all:
				if (!isCheckAll) {
					setCheckUncheckAll(true, arrAlbums, arrAlbumsSelected,
							mActionMode, mAlbumAdapter);
					isCheckAll = true;
				} else {
					setCheckUncheckAll(false, arrAlbums, arrAlbumsSelected,
							mActionMode, mAlbumAdapter);
					isCheckAll = false;
				}
				break;

			case R.id.menu_unhide:
				new Util.UnHideMedia(getActivity(), null, arrAlbumsSelected,
						navigationSelected, true, new onTask() {
							@Override
							public void onTaskComplete(Object object) {
								sendBroadcastAlbumHiden(arrAlbumsSelected);
								arrAlbums.removeAll(arrAlbumsSelected);
								mAlbumAdapter.notifyDataSetChanged();
								mActionMode.finish();
							}
						}).execute();
				break;
			case R.id.menu_delete:
				new Util.DeleteMediaHidden(getActivity(), null,
						arrAlbumsSelected, navigationSelected, true,
						new onTask() {
							@Override
							public void onTaskComplete(Object object) {
								sendBroadcastAlbumHiden(arrAlbumsSelected);
								arrAlbums.removeAll(arrAlbumsSelected);
								mAlbumAdapter.notifyDataSetChanged();
								mActionMode.finish();
							}
						}).execute();
				break;
			case R.id.menu_share:
				new Util.ShareFileHidden(getSherlockActivity(),
						arrAlbumsSelected, null, navigationSelected).execute();
				break;
			default:
				break;
			}

			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			isStartActionMode = false;
			setCheckUncheckAll(false, arrAlbums, arrAlbumsSelected,
					mActionMode, mAlbumAdapter);
			arrAlbumsSelected.clear();
		}

	}

	public void sendBroadcastAlbumHiden(ArrayList<ModelAlbum> arrAlbums) {
		Intent intent = new Intent();
		intent.setAction(Config.ACTION_SEND_ARR_ALBUM_HIDDEN_TO_STOCK);
		intent.putExtra(Config.KEY_ARR_ALBUM_HIDDEN, arrAlbums);
		getActivity().sendBroadcast(intent);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Config.REQUEST_CODE_ALBUMVIEW_HIDDEN:
			FragmentMain.IS_START_PASSWORD = false;
			if (position >= 0 && position < arrAlbums.size()) {
				if (getActivity().getString(R.string.all_media).equals(
						navigationSelected)) {
					arrAlbums.get(position)
							.setMediaOfAlbum(
									mDbHelper.getMediaOfAlbum(arrAlbums
											.get(position).idAlbum));
					arrAlbums
							.get(position)
							.setNumberMedia(
									mDbHelper.getNumberPhoto(arrAlbums
											.get(position).idAlbum)
											+ mDbHelper.getNumberVideo(arrAlbums
													.get(position).idAlbum));
				} else if (getActivity().getString(R.string.photos).equals(
						navigationSelected)) {
					arrAlbums.get(position).setMediaOfAlbum(
							mDbHelper.getMediaOfAlbumPhoto(arrAlbums
									.get(position).idAlbum));
					arrAlbums.get(position)
							.setNumberMedia(
									mDbHelper.getNumberPhoto(arrAlbums
											.get(position).idAlbum));
				} else {
					arrAlbums.get(position).setMediaOfAlbum(
							mDbHelper.getMediaOfAlbumVideo(arrAlbums
									.get(position).idAlbum));
					arrAlbums.get(position)
							.setNumberMedia(
									mDbHelper.getNumberVideo(arrAlbums
											.get(position).idAlbum));
				}
				mAlbumAdapter.notifyDataSetChanged();
			}
			break;
		case Config.REQUEST_CODE_START_ACTIVITY_GALLERY:
			FragmentMain.IS_START_PASSWORD = false;
			boolean isExists = false;
			for (ModelAlbum album : arrAlbums) {
				if (getString(R.string.default_album).equals(
						album.getNameAlbum())) {
					isExists = true;
					setMediaOfAlbum(album);
					break;
				}
			}
			ModelAlbum album = new ModelAlbum();
			album.setNameAlbum(getString(R.string.default_album));
			album.setIdAlbum(mDbHelper.getIdAlbumByNameAlbum(album
					.getNameAlbum()));

			if (!isExists) {
				ArrayList<ModelAlbum> arrAlbumsHidden = getNewAlbum(album);
				if (arrAlbumsHidden == null)
					arrAlbumsHidden = new ArrayList<ModelAlbum>();
				arrAlbums.addAll(arrAlbumsHidden);
			}
			mAlbumAdapter.notifyDataSetChanged();
			break;

		case Config.REQUEST_CODE_CAPTURE_IMAGE:
			FragmentMain.IS_START_PASSWORD = false;
			if (resultCode == Activity.RESULT_OK) {
				resultCamera(Config.TYPE_PHOTO);
			}
			break;
		case Config.REQUEST_CODE_CAPTURE_VIDEO:
			FragmentMain.IS_START_PASSWORD = false;
			if (resultCode == Activity.RESULT_OK) {
				resultCamera(Config.TYPE_VIDEO);
			}
			break;
		case Config.REQUEST_CODE_SHARE_FILE:
			FragmentMain.IS_START_PASSWORD = false;
			mActionMode.finish();
			break;
		default:
			break;
		}
	}

	// Receiver
	private void setMediaOfAlbum(ModelAlbum albumHidden) {
		if (getActivity().getString(R.string.all_media).equals(
				navigationSelected)) {
			albumHidden.setMediaOfAlbum(mDbHelper.getMediaOfAlbum(albumHidden
					.getIdAlbum()));
			albumHidden.setNumberMedia(mDbHelper.getNumberPhoto(albumHidden
					.getIdAlbum())
					+ mDbHelper.getNumberVideo(albumHidden.getIdAlbum()));
		} else if (getActivity().getString(R.string.photos).equals(
				navigationSelected)) {
			albumHidden.setMediaOfAlbum(mDbHelper
					.getMediaOfAlbumPhoto(albumHidden.getIdAlbum()));
			albumHidden.setNumberMedia(mDbHelper.getNumberPhoto(albumHidden
					.getIdAlbum()));
		} else {
			albumHidden.setMediaOfAlbum(mDbHelper
					.getMediaOfAlbumVideo(albumHidden.getIdAlbum()));
			albumHidden.setNumberMedia(mDbHelper.getNumberVideo(albumHidden
					.getIdAlbum()));
		}

	}

	private ArrayList<ModelAlbum> getNewAlbum(ModelAlbum album) {
		ArrayList<ModelAlbum> arrAlbumsHidden = new ArrayList<ModelAlbum>();
		if (getActivity().getString(R.string.all_media).equals(
				navigationSelected)) {
			arrAlbumsHidden = mDbHelper.getAllAlbumByNameAlbum(album
					.getNameAlbum());
		} else if (getActivity().getString(R.string.photos).equals(
				navigationSelected)) {
			arrAlbumsHidden = mDbHelper.getAllAlbumPhotosByNameAlbum(false,
					album.getNameAlbum());
		} else {
			arrAlbumsHidden = mDbHelper.getAllAlbumVideosNameAlbum(false,
					album.getNameAlbum(), null);
		}
		return arrAlbumsHidden;
	}

	private ArrayList<ModelAlbum> getNewAlbumByName(String nameAlbum) {
		ArrayList<ModelAlbum> arrAlbumsHidden = new ArrayList<ModelAlbum>();
		if (getActivity().getString(R.string.all_media).equals(
				navigationSelected)) {
			arrAlbumsHidden = mDbHelper.getAllAlbumByNameAlbum(nameAlbum);
		} else if (getActivity().getString(R.string.photos).equals(
				navigationSelected)) {
			arrAlbumsHidden = mDbHelper.getAllAlbumPhotosByNameAlbum(false,
					nameAlbum);
		} else {
			arrAlbumsHidden = mDbHelper.getAllAlbumVideosNameAlbum(false,
					nameAlbum, null);
		}
		return arrAlbumsHidden;
	}

	public void onClickMenuAddMedia() {
		Intent intent = new Intent(getActivity(),
				ActivityGalleryForResult.class);
		intent.putExtra(Config.KEY_NAME_ALBUM_HIDDEN,
				getString(R.string.default_album));
		intent.putExtra(Config.KEY_ID_ALBUM_HIDDEN, -1);
		startActivityForResult(intent,
				Config.REQUEST_CODE_START_ACTIVITY_GALLERY);
	}

	public void onClickMenuAddAlbum() {
		showDialogAddAlbum();
	}

	public void onClickMenuCamera() {
		camera = Camera.getInstance(getActivity());
		camera.startCamera(this, camera.getPathHiddenCam());
	}

	public void onClickMenuRecord() {
		camera = Camera.getInstance(getActivity());
		camera.startRecord(this, camera.getPathHiddenCam());
	}

	private void resultCamera(int type) {
		String stockPath = camera.pathCamera() + camera.getNamePhoto();
		String hiddenPath = camera.getCurrentFile().getAbsolutePath();
		String namePhoto = camera.getNamePhoto();
		String pathAlbum = camera.getPathHiddenCam();
		String nameAlbum = getString(R.string.hidden_camera);
		long idMedia = new Random().nextLong();
		ModelMedia media = new ModelMedia();
		media.setPathMediaHidden(hiddenPath);
		media.setPathMediaStock(stockPath);
		media.setIdMedia(idMedia);
		media.setDate(String.valueOf(System.currentTimeMillis()));
		media.setNameMedia(namePhoto);

		if (type == Config.TYPE_PHOTO) {
			media.setTypeMedia(Config.TYPE_PHOTO);
			media.setVideo(false);
		} else {
			media.setTypeMedia(Config.TYPE_VIDEO);
			media.setVideo(true);
		}

		long idAlbum = -1;
		if (mDbHelper.checkExistsAlbum(nameAlbum)) {
			idAlbum = mDbHelper.getIdAlbumByNameAlbum(nameAlbum);
		} else {
			int typeStore = Integer.parseInt(StringPref.getPreference(
					getActivity(), Config.KEY_STORAGE, "1"));
			idAlbum = mDbHelper.insertAlbum(nameAlbum, pathAlbum, typeStore);
		}

		media.setIdAlbum(idAlbum);
		mDbHelper.insertMedia(media);

		ModelAlbum album = new ModelMedia();
		album.setPathAlbum(pathAlbum);
		album.setNameAlbum(nameAlbum);
		album.setIdAlbum(idAlbum);

		boolean isExistsAlbum = false;
		for (ModelAlbum modelAlbum : arrAlbums) {
			if (modelAlbum.getNameAlbum().equals(
					getString(R.string.hidden_camera)))
				isExistsAlbum = true;
		}
		if (!isExistsAlbum)
			arrAlbums.add(0, album);

		mAlbumAdapter.notifyDataSetChanged();

		Intent intent = new Intent(getSherlockActivity(),
				ActivityAlbumView.class);
		intent.putExtra(Config.KEY_NAVIGATION_SELECTED, navigationSelected);
		intent.putExtra(Config.KEY_ALBUM_HIDDEN, album);
		startActivityForResult(intent, Config.REQUEST_CODE_ALBUMVIEW_HIDDEN);
	}
}
